package com.hap.filter;

import com.hap.spring.BeanFactory;
import com.hap.spring.ClassPathXmlApplocationContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class WebFilter implements Filter {
    private BeanFactory factory;

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //http://localhost:8080/spring_handwriting/userAction?method=addUser
        String path = request.getRequestURI();
        String actionName = path.substring(path.lastIndexOf("/") + 1);
        System.out.println(path + "-" + actionName);
        Object obj = factory.getBean(actionName);
        String methodName = request.getParameter("method");

        try {
            Method method = obj.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            String result = (String) method.invoke(obj, request, response);
            request.getRequestDispatcher(result).forward(request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    public void init(FilterConfig config) throws ServletException {
        factory = new ClassPathXmlApplocationContext();
    }

}
